<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button v-if="permissionList.addBtn" @click.stop="handleSave" type="primary" icon="el-icon-plus" size="small">新 增</el-button>
      </template>

      <template slot-scope="scope" slot="menu">
        <el-button v-if="permissionList.addBtn" @click.stop="handleEdit(scope.row, scope.index)" icon="el-icon-edit" size="small" type="text">编 辑</el-button>
        <el-button v-if="permissionList.delBtn" @click.stop="delWhite(scope.row)" icon="el-icon-delete" type="text" size="small">删 除</el-button >
      </template>

      <template slot-scope="{ disabled, size }" slot="beginTimeSearch">
        <el-date-picker
          v-model="search.beginTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          @change="beginTimeChange"
          placeholder="请输入 扣费开始日期"
        ></el-date-picker>
      </template>
      <template slot-scope="{ disabled, size }" slot="endTimeSearch">
        <el-date-picker
          v-model="search.endTime"
          type="datetime"
          default-time="23:59:59"
          value-format="yyyy-MM-dd HH:mm:ss"
          @change="endTimeChange"
          placeholder="请输入 扣费结束日期"
        ></el-date-picker>
      </template>
    </avue-crud>

    <el-dialog
      :title="dialogText"
      top="4%"
      :width="screenWidth>1920?'30%':(screenWidth<=1920 && screenWidth>1500)?'50%':'80%'"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      :before-close="handleClose"
    >
      <el-form :model="addForm" :rules="rules" ref="addForm" size="small" label-width="160px" class="demo-addForm">
        <div class="f_s16">生效规则</div>
        <el-form-item label="政策名称" prop="policyName">
          <el-input v-model="addForm.policyName" class="haruyuki-width-50"  @input="$forceUpdate()"></el-input>
        </el-form-item>
        <el-form-item label="生效通道" prop="aisleCodeList">
          <el-select v-model="addForm.aisleCodeList" clearable multiple placeholder="请选择生效通道" class="haruyuki-width-50">
            <el-option :label="item.aisleName" :value="item.aisleCode" v-for="item in aisleList" :key="item.aisleCode"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商户开通后" prop="merchantDay">
          <el-input-number
            class="haruyuki-width-50"
            v-model="addForm.merchantDay"
            :min="0"
            controls-position="right"
          ></el-input-number>
          <span class="p_l10">天生效</span>
        </el-form-item>
        <el-form-item label="服务商开通后" prop="serviceDay">
          <el-input-number
            class="haruyuki-width-50"
            v-model="addForm.serviceDay"
            :min="0"
            controls-position="right"
          ></el-input-number>
          <span class="p_l10">天生效</span>
        </el-form-item>
        <el-form-item label="服务商本级当天交易" prop="serviceTradeCount">
          <el-input-number
            class="haruyuki-width-50"
            v-model="addForm.serviceTradeCount"
            :min="0"
            controls-position="right"
          ></el-input-number>
          <span class="p_l10">笔后生效</span>
        </el-form-item>
        <el-form-item label="服务商白名单">
          <el-button type="primary" @click="serviceDialog = true">点击查看或设置</el-button>
        </el-form-item>
        <el-form-item label="商户白名单">
          <el-button type="primary" @click="merchantDialog = true">点击查看或设置</el-button>
        </el-form-item>
        <el-form-item label="是否生效" prop="isOn">
          <el-radio-group v-model="addForm.isOn">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <div  class="f_s16">计算规则</div>
        <el-form-item label="" prop="policyType">
          <el-checkbox-group v-model="addForm.policyType" @change="checkBoxChange">
            <el-checkbox :label="1" name="type">贷记转云闪付</el-checkbox>
            <el-checkbox :label="2" name="type">贷记转借记</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <div v-if="ysfshow">
          <div class="f_s16 p_b4">贷记转云闪付</div>
          <el-form-item label="交易金额大于" prop="ysfPolicy.tradeAmount">
            <el-input-number
              class="haruyuki-width-50"
              v-model="addForm.ysfPolicy.tradeAmount"
              :min="0"
              controls-position="right"
            ></el-input-number>
            <span class="p_l10">元</span>
          </el-form-item>
          <el-form-item label="云闪付交易比例低于" prop="ysfPolicy.tradeRate">
            <el-input-number
              class="haruyuki-width-50"
              v-model="addForm.ysfPolicy.tradeRate"
              :precision="2"
              :step="0.01"
              :min="0"
              :max="100"
              controls-position="right"
            ></el-input-number>
            <span class="p_l10">%</span>
          </el-form-item>
          <el-form-item label="交易比例按照" prop="ysfPolicy.tradeType">
            <el-radio-group v-model="addForm.ysfPolicy.tradeType">
              <el-radio :label="1">日</el-radio>
              <el-radio :label="2">周</el-radio>
              <el-radio :label="3">月</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <div v-if="jjkshow">
          <div class="f_s16 p_b4">贷记转借记</div>
          <el-form-item label="交易金额大于" prop="debitPolicy.tradeAmount">
            <el-input-number
              class="haruyuki-width-50"
              v-model="addForm.debitPolicy.tradeAmount"
              :min="0"
              controls-position="right"
            ></el-input-number>
            <span class="p_l10">元</span>
          </el-form-item>
          <el-form-item label="借记卡交易比例低于" prop="debitPolicy.tradeRate">
            <el-input-number
              class="haruyuki-width-50"
              v-model="addForm.debitPolicy.tradeRate"
              :precision="2"
              :step="0.01"
              :min="0"
              :max="100"
              controls-position="right"
            ></el-input-number>
            <span class="p_l10">%</span>
          </el-form-item>
          <el-form-item label="交易比例按照" prop="debitPolicy.tradeType">
            <el-radio-group v-model="addForm.debitPolicy.tradeType">
              <el-radio :label="1">日</el-radio>
              <el-radio :label="2">周</el-radio>
              <el-radio :label="3">月</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="() => { dialogVisible = false; initEmpty(); }">取 消</el-button>
        <el-button style="margin-left:10px;" size="small" type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="服务商白名单"
      top="3%"
      width="96%"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="serviceDialog"
      v-if="serviceDialog"
      :before-close="handleCloseService"
    >
      <serviceWhite ref="serviceWhite" :serviceArr="addForm.serviceList"/>
    </el-dialog>

    <el-dialog
      title="商户白名单"
      top="3%"
      width="96%"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="merchantDialog"
      v-if="merchantDialog"
      :before-close="handleClosemerchant"
    >
      <merchantWhite ref="merchantWhite" :merhcantArr="addForm.merchantList"/>
    </el-dialog>
  </basic-container>
</template>

<script>
import { mapGetters } from "vuex";
import selectPage from "@/components/select-page/select-page";
import serviceWhite from "./components/deal/serviceWhite";
import merchantWhite from "./components/deal/merchantWhite";
import { getList,getDetail,apiSubmit,apiDel } from "@/api/rb-oem/optimizePolicies/deal";
import { getAisleOemList } from "@/api/rb-oem/serviceinfo/service_info";

export default {
  components: { selectPage,serviceWhite,merchantWhite },
  data() {
    return {
      ysfshow:false,
      jjkshow:false,
      screenWidth: document.documentElement.clientWidth,
      query: {},
      search: {},
      loading: true,
      dialogText: '',
      dialogType: '',
      dialogVisible: false,
      
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: false,
        searchSpan: 8,
        // searchMenuSpan: 8,
        columnBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn:false,
        searchLabelWidth: 120, //搜索框标题宽度
        column: [
          {
            label: "政策编号",
            prop: "optimizeCode",
            type: "input",
            overHidden: true,
          },
          {
            label: "政策名称",
            prop: "policyName",
            type: "input",
            search: true,
            overHidden: true,
          },
          {
            label: "是否启用",
            searchLabel: "是否启用",
            prop: "isOn",
            type: "select",
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=yes_or_no",
            dataType: "number",
            slot: true,
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            overHidden: true,
          },
          {
            label: "所属通道",
            prop: "aisleCode",
            type: "select",
            display: false,
            overHidden: true,
            search: true,
            searchOrder: 0,
            hide:true,
            props: {
              label: "aisleName",
              value: "aisleCode",
              desc: "aisleCode"
            },
            dicData:[]
          },
          {
            label: "所属通道",
            prop: "aisleCodeName",
            type: "input",
            display: false,
            overHidden: true,
          },
          {
            label: "创建时间",
            prop: "createTime",
            type: "input",
            display: false,
            overHidden: true,
          },
          {
            label: "创建开始日期",
            prop: "beginTime",
            // type: "datetime",
            search: true,
            hide: true,
            display: false
          },
          {
            label: "创建结束日期",
            prop: "endTime",
            // type: "datetime",
            search: true,
            hide: true,
            display: false
          }
        ],
      },
      data: [],
      addForm:{
        policyName:'',//政策名称
        aisleCodeList:[],//生效通道
        merchantDay:"",
        serviceDay:"",
        serviceTradeCount:"",
        policyType:[],
        isOn:0,
        ysfPolicy:{
          policyType:"",
          tradeAmount:'',//交易金额
          tradeRate:'',//交易比例
          tradeType:3//交易类型(1.日2.周3.月)
        },
        debitPolicy:{
          policyType:"",
          tradeAmount:'',//交易金额
          tradeRate:'',//交易比例
          tradeType:3//交易类型(1.日2.周3.月)
        },
        serviceList:[],
        merchantList:[]
      },
      rules:{
        policyName: [
          {required: true, message: "请输入政策名称", trigger: ["blur"]}
        ],
        aisleCodes: [
          {required: true, message: "请选择生效通道", trigger: ["change","blur"]}
        ],
        merchantDay: [
          {required: true, message: "请输入天数", trigger: ["blur"]}
        ],
        serviceDay: [
          {required: true, message: "请输入天数", trigger: ["blur"]}
        ],
        serviceTradeCount: [
          {required: true, message: "请输入笔数", trigger: ["blur"]}
        ],
        policyType:[
          {required: true, message: "请选择", trigger: ["change","blur"]}
        ],
        'ysfPolicy.tradeAmount':[
          {required: true, message: "请输入", trigger: ["change","blur"]}
        ],
        'ysfPolicy.tradeRate':[
          {required: true, message: "请输入", trigger: ["change","blur"]}
        ],
        'debitPolicy.tradeAmount':[
          {required: true, message: "请输入", trigger: ["change","blur"]}
        ],
        'debitPolicy.tradeRate':[
          {required: true, message: "请输入", trigger: ["change","blur"]}
        ],
      },
      serviceDialog:false,
      merchantDialog:false,
      aisleList:[]
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.deal_view, false),
        delBtn: this.vaildData(this.permission.del, false),
        addBtn: this.vaildData(this.permission.opt_add, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  created(){
    this.getAisleSelect();
    this.$refs.crud.doLayout();
  },
  methods: {
    handleCloseService(done){
      this.addForm.serviceList = this.$refs.serviceWhite.allData
      done()
    },
    handleClosemerchant(done){
      this.addForm.merchantList = this.$refs.merchantWhite.allData
      done()
    },
    delWhite(row){
      let that = this;
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        apiDel(row.id).then(res=>{
          that.onLoad(that.page)
        })
      });
    },
    /* 通道列表 */
    getAisleSelect() {
      getAisleOemList("-1", "-1").then((res) => {
        this.aisleList = res.data.data.records;
        const column = this.findObject(this.option.column, "aisleCode");
        column.dicData = this.aisleList;
      });
    },
    checkBoxChange(arr){
      if(arr.length==0){
        this.ysfshow = false;
        this.jjkshow = false;
        this.addForm.ysfPolicy = {
          tradeAmount:'',//交易金额
          tradeRate:'',//交易比例
          tradeType:3//交易类型(1.日2.周3.月)
        };
        this.addForm.debitPolicy = {
          tradeAmount:'',//交易金额
          tradeRate:'',//交易比例
          tradeType:3//交易类型(1.日2.周3.月)
        };
      }else if(arr.length==1){
        if(arr[0] === 1){
          this.ysfshow = true;
          this.jjkshow = false;
          this.addForm.debitPolicy = {
            tradeAmount:'',//交易金额
            tradeRate:'',//交易比例
            tradeType:3//交易类型(1.日2.周3.月)
          };
        }else{
          this.ysfshow = false;
          this.jjkshow = true;
          this.addForm.ysfPolicy = {
            tradeAmount:'',//交易金额
            tradeRate:'',//交易比例
            tradeType:3//交易类型(1.日2.周3.月)
          };
        }
      }else{
        this.ysfshow = true;
        this.jjkshow = true;
      }
    },
    beginTimeChange() {
      if(this.search.endTime){
        if(Date.parse(this.search.beginTime) > Date.parse(this.search.endTime)){
          this.$alert('开始日期不能大于结束日期', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          .then(() => (this.search.beginTime = ""))
          .catch(() => (this.search.beginTime = ""))
        }
      }
    },
    endTimeChange() {
      if(this.search.beginTime){
        if(Date.parse(this.search.endTime) < Date.parse(this.search.beginTime)){
          this.$alert('结束日期不能小于开始日期', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          .then(() => (this.search.endTime = ""))
          .catch(() => (this.search.endTime = ""))
        }
      }
    },
    // 提交保存
    submit() {
      let that = this;
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let param ={
            ...that.addForm,
            aisleCode:that.addForm.aisleCodeList.join(',')
          }

          that.addForm.policyType.forEach((item)=>{
            if( item === 1 ){
              that.addForm.ysfPolicy.policyType = 1;
            }else if( item ===2 ){
              that.addForm.debitPolicy.policyType = 2
            }
          })
          apiSubmit(param).then(res=>{
            that.dialogVisible = false;
            that.initEmpty();
            that.onLoad(this.page)
          })
        } else {
          return false;
        }
      });
    },
    handleSave() {
      this.dialogVisible = true;
      this.dialogType = 'add';
      this.dialogText = "新增";
    },
    handleEdit(row) {
      this.dialogVisible = true;
      this.dialogType = 'edit';
      this.dialogText = "编辑";
      this.dialogVisible = true;
      getDetail(row.id).then((res) => {
        let data = res.data.data;
        this.addForm.id = data.id;
        this.addForm.policyName = data.policyName;
        this.addForm.aisleCodeList = data.aisleCode?data.aisleCode.split(','):'';
        this.addForm.merchantDay = data.merchantDay;
        this.addForm.serviceDay = data.serviceDay;
        this.addForm.serviceTradeCount = data.serviceTradeCount;
        this.addForm.isOn = data.isOn;

        this.addForm.ysfPolicy = {
          tradeAmount:data.ysfPolicy.tradeAmount,//交易金额
          tradeRate:data.ysfPolicy.tradeRate,//交易比例
          tradeType:data.ysfPolicy.tradeType//交易类型(1.日2.周3.月)
        }

        this.addForm.debitPolicy = {
          tradeAmount:data.debitPolicy.tradeAmount,//交易金额
          tradeRate:data.debitPolicy.tradeRate,//交易比例
          tradeType:data.debitPolicy.tradeType//交易类型(1.日2.周3.月)
        }

        if(data.ysfPolicy.policyType){
          this.addForm.policyType.push(data.ysfPolicy.policyType)
          this.ysfshow = true;
        }
        if(data.debitPolicy.policyType){
          this.addForm.policyType.push(data.debitPolicy.policyType)
          this.jjkshow = true;
        }

        this.addForm.serviceList = data.serviceList;
        this.addForm.merchantList = data.merchantList;
      });
    },
    handleClose(done) {
      this.initEmpty();
      done()
    },
    initEmpty() {
      this.ysfshow = false;
      this.jjkshow = false;
      
      this.addForm = {
        policyName:'',//政策名称
        aisleCodeList:[],//生效通道
        merchantDay:"",
        serviceDay:"",
        serviceTradeCount:"",
        policyType:[],
        isOn:0,
        ysfPolicy:{
          policyType:"",
          tradeAmount:'',//交易金额
          tradeRate:'',//交易比例
          tradeType:3//交易类型(1.日2.周3.月)
        },
        debitPolicy:{
          policyType:"",
          tradeAmount:'',//交易金额
          tradeRate:'',//交易比例
          tradeType:3//交易类型(1.日2.周3.月)
        },
        serviceList:[],
        merchantList:[]
      }
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then((res) => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        // this.selectionClear();
      });
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    }
  }
};
</script>

<style lang="scss" scoped>
.f_s16{
  font-size: 16px;
}
.p_b4{
  padding-bottom: 4px;
}
.p_l10{
  padding-left: 10px;
}

/deep/ .el-dialog__body{
  padding: 0 10px 20px 20px;

}

/deep/ .el-input-number__decrease,
/deep/ .el-input-number__increase{
  display: none;
}
/deep/ .el-input-number.is-controls-right .el-input__inner{
  padding-right:15px;
  text-align: left;
}
.haruyuki-width-50{
  width: 80%;
}
</style>
